#include "xdecode.h"
extern "C" {
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libavutil/error.h>
}
#include <stdexcept>


XDecode::XDecode(/* args */) : ifmt_ctx(nullptr), dec_ctx(nullptr), dec_frame(nullptr){}

XDecode::~XDecode()
{

}

bool XDecode::Open(const char* file_name)
{
    int ret = 0;
    AVCodecContext* codec_ctx;
    if ((ret = avformat_open_input(&ifmt_ctx, file_name, NULL, NULL)) < 0)
    {
        // throw std::runtime_error("Failed to open input file");
        av_log(NULL, AV_LOG_ERROR, "can't input file\n");
        return ret;
    }

    if ((ret = avformat_find_stream_info(ifmt_ctx, NULL)) < 0) 
    {
        av_log(NULL, AV_LOG_ERROR, "can't find stream information\n");
        avformat_close_input(&ifmt_ctx);
        return ret;
    }

    // Allocate decoder contexts and frames
    for (unsigned int  i = 0; i < ifmt_ctx->nb_streams; i++) // nb_streams音视频流的个数
    {
        AVStream *stream = ifmt_ctx->streams[i];
        dec = avcodec_find_decoder(stream->codecpar->codec_id);
        
        if (!dec)
        {
            av_log(NULL, AV_LOG_ERROR, "Failed to find decoder for stream\n");
            return AVERROR_DECODER_NOT_FOUND;
        }
        codec_ctx = avcodec_alloc_context3(dec);
        if (!codec_ctx) 
        {
            av_log(nullptr, AV_LOG_ERROR, "Failed to allocate the decoder context for stream #%u\n", i);
            return AVERROR(ENOMEM);
        }
        
        ret = avcodec_parameters_to_context(codec_ctx, stream->codecpar);

        if (ret < 0)
        {
            // av_log()
        }
    }
    
    


    return ret;
    
}


void XDecode::Clean()
{
    for (unsigned int i = 0; i < ifmt_ctx->nb_streams; i++)
    {
        // av_frame_free(&dec)
    }
}
